package com.wiscamp.ninechapters.problems.application.services;

import com.wiscamp.ninechapters.problems.application.assemblers.AssignmentAssembler;
import com.wiscamp.ninechapters.problems.application.dto.commands.tasks.CreateAssignmentCommand;
import com.wiscamp.ninechapters.problems.application.dto.commands.tasks.UpdateAssignmentCommand;
import com.wiscamp.ninechapters.problems.application.dto.vo.tasks.AssignmentVO;
import com.wiscamp.ninechapters.problems.domain.repositories.AssignmentRepository;
import com.wiscamp.ninechapters.problems.domain.services.AssignmentService;
import cube.ddd.application.BaseAppService;
import cube.ddd.application.command.DeleteCommand;
import cube.ddd.aspect.HandleServiceException;
import cube.ddd.utils.AppServiceUtils;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import org.springframework.stereotype.Service;

import java.util.Collection;

@Service
public class AssignmentAppService extends BaseAppService {
    private final AssignmentRepository assignmentRepository;

    private final AssignmentService assignmentService;

    public AssignmentAppService(AssignmentRepository assignmentRepository, AssignmentService assignmentService) {
        this.assignmentRepository = assignmentRepository;
        this.assignmentService = assignmentService;
    }

    @HandleServiceException
    public AssignmentVO getAssignment(@Min(0) long assignmentId) {
        return AppServiceUtils.getById(assignmentId, assignmentRepository::getAssignment,
                AssignmentAssembler.Instance::toAssignmentVO);
    }

    @HandleServiceException
    public Collection<AssignmentVO> getAssignmentsBySet(@Min(0) long setId) {
        return AppServiceUtils.getListById(setId, assignmentRepository::getAssignmentsBySet,
                AssignmentAssembler.Instance::toAssignmentVO);
    }

    @HandleServiceException
    public AssignmentVO createAssignment(@NotNull CreateAssignmentCommand command) {
        return AppServiceUtils.createOrUpdateBy(command, command.getOperatorId(), assignmentService::createAssignment,
                AssignmentAssembler.Instance::toAssignmentVO, AssignmentAssembler.Instance::fromCreateCommand);
    }

    @HandleServiceException
    public AssignmentVO updateAssignment(@NotNull UpdateAssignmentCommand command) {
        return AppServiceUtils.createOrUpdateBy(command, command.getOperatorId(), assignmentService::updateAssignment,
                AssignmentAssembler.Instance::toAssignmentVO, AssignmentAssembler.Instance::fromUpdateCommand);
    }

    @HandleServiceException
    public boolean deleteAssignment(@NotNull DeleteCommand command) {
        return AppServiceUtils.delete(command.getId(), command.getOperatorId(), assignmentService::deleteAssignment);
    }
}
